package com.coc.ofhibernate.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactorySecond",
        transactionManagerRef = "transactionManagerSecond",
        basePackages={"com.coc.ofhibernate.repository.second"}
//        basePackageClasses = {SecondRepository.class}
)
public class SecondConfig {

//
//    @Autowired
//    private Environment env;

    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource datasource2;// 自动注入配置好的数据源


    @Bean("entityManagerFactorySecond")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(datasource2);
        factory.setPackagesToScan("com.coc.ofhibernate.entity.database2");

        factory.setJpaVendorAdapter(vendorAdapter);

//        Properties jpaProperties = new Properties();
//        jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
//        jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
//        factory.setJpaProperties(jpaProperties);
        return factory;

    }

    @Bean("transactionManagerSecond")
    public PlatformTransactionManager transactionManagerSecond() {
        EntityManagerFactory factory = entityManagerFactorySecond().getObject();
        return new JpaTransactionManager(factory);
    }
}
